package com.atguigu.dga.assess.assessor;

import com.alibaba.fastjson.JSON;
import com.atguigu.dga.assess.bean.AssessParam;
import com.atguigu.dga.assess.bean.GovernanceAssessDetail;
import com.atguigu.dga.assess.bean.GovernanceMetric;
import com.atguigu.dga.meta.bean.TableMetaInfo;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;

/**
 * Created by Smexy on 2023/10/28
 */
public abstract class AssessorTemplate
{
    //关键的考评方法,交给子类实现，抽象的
    protected abstract void assess(AssessParam param, GovernanceAssessDetail detail) throws Exception;

    //把要执行的流程定义好
    public GovernanceAssessDetail doAssess(AssessParam param){

        GovernanceAssessDetail detail = new GovernanceAssessDetail();
        TableMetaInfo metaInfo = param.getMetaInfo();
        GovernanceMetric metric = param.getMetric();
        String assessDate = param.getAssessDate();
        //封装
        detail.setAssessDate(assessDate);
        detail.setTableName(metaInfo.getTableName());
        detail.setSchemaName(metaInfo.getSchemaName());
        detail.setMetricId(metric.getId().toString());
        detail.setMetricName(metric.getMetricName());
        detail.setGovernanceType(metric.getGovernanceType());
        detail.setTecOwner(metaInfo.getTableMetaInfoExtra().getTecOwnerUserName());
        detail.setCreateTime(new Timestamp(System.currentTimeMillis()));
        detail.setGovernanceUrl(metric.getGovernanceUrl());
        //假设都是没问题的
        detail.setAssessScore(BigDecimal.TEN);

        //调用关键的考评方法
        try {
            assess(param,detail);
        } catch (Exception e) {
            detail.setIsAssessException("1");
            PrintWriter printWriter = new PrintWriter(new StringWriter());
            e.printStackTrace(printWriter);
            String msg = printWriter.toString();
            //防止异常信息过多，无法写入数据库
            detail.setAssessExceptionMsg(msg.substring(0,Math.min(2000,msg.length())));
            //调试时，建议打开。部署时，要注释掉。
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return detail;
    }

    /**
     *  交给考评器打分使用
     * @param score
     * @param problem
     * @param comment
     * @param detail
     * @param ifReplaceUrl
     * @param id
     */
    protected void assessScore(BigDecimal score,String problem,String comment,GovernanceAssessDetail detail,
                               boolean ifReplaceUrl,Long id){

        detail.setAssessScore(score);
        detail.setAssessProblem(problem);
        detail.setAssessComment(comment);
        if (ifReplaceUrl){
            detail.setGovernanceUrl(
                detail.getGovernanceUrl().replace("{id}",id.toString())
            );
        }
    }

    protected Integer getIntegerValueFromConfig(AssessParam param,String name){
        return JSON.parseObject(param.getMetric().getMetricParamsJson()).getInteger(name);
    }


}
